#include<stdio.h>
#include<unistd.h>
#include<string.h>

int main(){
    //匿名管道的创建一定要在创建子进程之前(因为要复制父进程的文件描述符)
    int pipefd[2];
    int ret=pipe(pipefd);
    if(ret<0){
        perror("pipe error");
        return -1;
    }

    pid_t cpid=fork();
    if(cpid<0){
        perror("fork error");
        return -1;
    }
    else if(cpid==0){
        //child
        close(pipefd[1]);
        char buf[1024]={0};
        //pipefd[0]用于从管道读取数据
        int ret=read(pipefd[0],buf,1023);
        if(ret<0){
           perror("read error");
           return -1;
        }
        else if(ret==0){
            printf("所有写端被关闭!\n");
            return -1;
        }
        printf("buf[%s]\n",buf);
        
    }
    else{
        close(pipefd[0]);
        printf("write over\n");
        sleep(1);
        //parent
        char *buf="简单的匿名管道！";
        //pipefd[1]用于向管道写入数据
        write(pipefd[1],buf,strlen(buf));

    }
    return 0;
}
